// Client

AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")

// Allowed

ENT.Allowed = {
	"prop_physics",
	"player"
}

// Include

include('shared.lua')

// Initialize

function ENT:Initialize()
	self.Entity:PhysicsInit(SOLID_VPHYSICS)
	self.Entity:SetMoveType(MOVETYPE_VPHYSICS)
	self.Entity:SetSolid(SOLID_VPHYSICS)
	self.Entity:SetUseType(ONOFF_USE)
end

// Validation

function ENT:Validation(Entity)
	for K, V in pairs(self.Allowed) do
		if (Entity:GetClass() == V) then
			return true
		end
	end
	
	return false
end

// Friendly

function ENT:Friendly(Entity)
	local Player = self:GetPlayer()
	
	if (Entity == Player) then return true end
	
	if (PropSecure) then
		if (PropSecure.IsPlayers) then
			if (PropSecure.IsPlayers(Player, Entity)) then
				return true
			end
		end
	end
	
	return false
end

// Think

function ENT:Think()
	local Position = self.Entity:GetPos()
	local Radius   = self:GetEntityRadius()
	local Type     = self:GetEntityType()
	local Current  = self.Entity:GetNetworkedEntity("Target")
	local Delay    = 0.05
	
	// Check
	
	local Valid = Current:IsValid()
	
	if not (Valid) then
		Current = nil
	else
		local Ang = (Position - Current:GetPos()):Length()
		
		if (Ang > Radius) then
			Current = nil
		end
	end
	
	// Check
	
	if not (Current) then
		self.Entity:SetNetworkedInt("Target", 0)
	end
	
	// Sphere
	
	local Area = ents.FindInSphere(Position, Radius)
	
	for K, V in pairs(Area) do
		if (self:Validation(V)) then
			if not (self:Friendly(V)) then
				local Smaller = false
				
				if (Current) then
					local Entity = (Position - Current:GetPos()):Length()
					
					local Other = (Position - V:GetPos()):Length()
					
					Smaller = (Other < Entity)
				end
		
				if not (Current) or (Current == V) or (Smaller) then
					local Ang = V:GetPos()
					
					local Pl = V:IsPlayer() if (Pl) then Ang = Ang + Vector(0, 0, 32) end
					
					Ang = Ang - Position
					
					Ang = Ang:Normalize()
					
					local Trace = {}
					
					Trace.start = Position
					Trace.endpos = Position + (Ang * Radius)
					Trace.filter = self.Entity
					
					local TR = util.TraceLine(Trace)
				 
					if (TR.Entity and TR.Entity == V) then
						Delay = PerimeterTurret.List[Type](self:GetPlayer(), self.Entity, TR.Entity, Position, Ang)
						
						self.Entity:SetNetworkedEntity("Target", V)
						
						self.Entity:SetNetworkedInt("Target", 1)
					end
				end
			end
		end
	end
	
	self.Entity:NextThink(CurTime() + Delay)
	
	return true
end